package com.xiaouyudeguang.common.resource;

import com.xiaouyudeguang.common.collect.MapBuilder;
import com.xiaouyudeguang.common.config.OSSConfig;
import com.xiaouyudeguang.common.respose.ResultDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/file")
public class OSSController {

    @Autowired
    private OSSConfig ossConfig;

    @Value("${aliyun.oss.urlPrefix}")
    private String urlPrefix;

    @PostMapping(value = "/upload")
    public ResultDto<String> upload(@RequestParam(value = "file") MultipartFile file) throws IOException {
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        String objectName = UUID.randomUUID() + "." + suffix;
        return ResultDto.ok(ossConfig.upload(file.getInputStream(), objectName));
    }

    @PostMapping(value = "/uploadFile")
    public ResultDto<Map<String, String>> uploadFile(@RequestParam(value = "file") MultipartFile file) throws IOException {
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        String objectName = UUID.randomUUID() + "." + suffix;
        Map<String, String> result = MapBuilder.builder().put("name", file.getOriginalFilename()).put("url", ossConfig.upload(file.getInputStream(), objectName)).build();
        return ResultDto.ok(result);
    }

    @PostMapping(value = "/uploadRichText")
    public Map<String, Object> uploadRichText(@RequestParam(value = "file") MultipartFile file) throws IOException {
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        String objectName = UUID.randomUUID() + "." + suffix;
        try {
            Map<String, Object> data = MapBuilder.of("url", urlPrefix + ossConfig.upload(file.getInputStream(), objectName));
            return MapBuilder.builder().put("errno", 0).put("data", data).build();
        } catch (Exception e){
            return MapBuilder.builder().put("errno", 1).put("message", e.getMessage()).build();
        }
    }
}

